#!/usr/bin/env python3
# -*- coding: utf-8 -*-
##############################################
# @Author: DengLibin 榆霖
# @Date: Create in 2022-03-04 14:28:14
# @Description: 分布式进程
##############################################
'module name'
__author__ = 'DengLibin'
#if __name__ == '__main__':

import queue
import random
import time
from multiprocessing.managers import BaseManager

 # 从BaseManager继承的QueueManager:
class QueueManager(BaseManager):
    pass

# 分布式进程 机器二 worker进程
def run_worker():
    print("-----------------------------------worker进程----------------------------------")
    # 由于这个QueueManager只从网络上获取Queue，所以注册时只提供名字:
    QueueManager.register('get_task_queue')
    QueueManager.register('get_result_queue')
    
    # 连接到服务器，也就是运行master进程的机器:
    server_addr = '127.0.0.1'
    print('Connect to server %s...' % server_addr)
    # 端口和验证码注意保持与master进程设置的完全一致:
    m = QueueManager(address=(server_addr, 5000), authkey=b'abc')
    # 从网络连接:
    m.connect()
    
    # 获取Queue的对象:
    task = m.get_task_queue()
    result = m.get_result_queue()
    # 从task队列取任务,并把结果写入result队列:
    for i in range(10):
        try:
            n = task.get(timeout=1)
            print('run task %d * %d...' % (n, n))
            r = '%d * %d = %d' % (n, n, n*n)
            time.sleep(1)
            result.put(r)
        except queue.Empty:
            print('task queue is empty.')
    # 处理结束:
    print('worker exit.')
    
    
if __name__ == '__main__':
    run_worker()
